<template>
  <view class="my-settle-container">
    <!-- 全选 -->
    <label class="radio" @click="changeAllState">
      <radio color="#C00000" :checked="isFullCheck" /><text>全选</text>
    </label>
    <!-- 合计 -->
    <view class="amount-box">
      <text class="amount-title">合计：</text>
      <text class="amount-num">￥{{payAmount | tofixed}}<text style="font-size:12px;">（万分一）</text></text>
    </view>
    <!-- 结算按钮 -->
    <view class="btn-settle" @click="settlement">结算({{checkedCount}})</view>
  </view>
</template>

<script>
  import {mapState, mapGetters, mapMutations} from 'vuex'
  export default {
    name:"my-settle",
    data() {
      return {
        
      };
    },
    computed: {
      ...mapGetters('m_cart', ['checkedCount', 'goodsTotal', 'payAmount', 'addrstr']),
      ...mapGetters('m_user', ['addrstr']),
      ...mapState('m_user', ['token', 'redirectInfo', 'address', 'uid']),
      ...mapState('m_cart', ['cart']),
      // 购物车全选按钮的计算属性
      isFullCheck(){
        return this.checkedCount === this.goodsTotal
      }
    },
    filters: {
      tofixed(val) {
        return parseFloat(val).toFixed(2)
      }
    },
    methods: {
      ...mapMutations('m_cart', ['updateAllGoodsState', 'removeGoodsById']),
      ...mapMutations('m_user', ['updateRedirectInfo']),
      // 根据全选按钮是否选中，更改购物车所有商品是否选中
      changeAllState() {
        this.updateAllGoodsState(!this.isFullCheck)
      },
      // 点击结算按钮处理函数
      settlement() {
        if(!this.checkedCount) return uni.$showMsg('请选择要结算的商品！', 1500, 'none')
        if(!this.addrstr) return uni.$showMsg('请选择收货地址！', 1500, 'none')
        if(!this.token) {
          // 3秒内每秒定时器显示一次未登录跳转提示
          let secs = 3
          let timer = setInterval(() => {
            if(secs <= 0) {
              clearInterval(timer)
              return uni.switchTab({
                url: '/pages/my/my',
                // 从[购物车]页面切换到[我的]页面后，保存购物车页面到vuex中，以便登录后，跳转到结算页面
                complete:(res) => {  //res.errMsg='switchTab:ok'
                  let info = {
                    openType: 'switchTab',
                    from: '/pages/cart/cart'
                  }
                  this.updateRedirectInfo(info)
                }
              })
            }
            this.showTips(secs)
            secs--
          }, 1000)
        }
        
        // 以上条件校验通过后，调用函数发起后端请求获取订单号
        this.payOrder();
      },
      // 发起后端请求获取订单号的函数
      async payOrder(){
        // 组织订单信息对象，以便发起获取订单号请求
        const orderInfo = {
          // order_price: this.payAmount,
          // 取支付金额的万分之一，如果仍小于0.01，则最小需支付0.01元
          // 保留两位小数，不四舍五入
          // order_price: this.payAmount*(1/10000) > 0.01 ? parseInt(this.payAmount*(1/10000)*100)/100 : 0.01,
          // 保留两位小数，四舍五入
          order_price: this.payAmount*(1/10000) > 0.01 ? Number(this.payAmount*(1/10000)).toFixed(2) : 0.01,
          consignee_addr: {
            name: this.address.userName,
            tel: this.address.telNumber,
            addr: this.addrstr
          },
          order_detail: this.cart.filter(x => x.goods_state).map(x => ({
            goods_id: x.goods_id,
            goods_name: x.goods_name,
            goods_price: x.goods_price,
            goods_small_logo: x.goods_small_logo,
            counts: x.goods_count,
            selectStatus: x.goods_state
          })
          ),
          goods: this.cart.filter(x => x.goods_state).map(x => ({
            goods_id: x.goods_id,
            goods_number: x.goods_count,
            goods_price: x.goods_price
          })
          ),
          prefix: 'HM',  // 订单自定义前缀标识符
          uid: this.uid  // 在后端生成的订单号加上5位数的uid（不够5位前面用0补足），以方便标识是哪个用户的订单
        }
        console.log('获取订单号发送的请求参数', orderInfo)
        // 配置自己服务器的请求根路径前缀
        uni.$http.baseUrl = 'https://api.sirurl.cn';
        // 发送请求获取订单号
        const {data: res} = await uni.$http.post('/api/public/v1/my/orders/create', orderInfo)  // 这里在后端thinkphp配置了路由映射
        console.log('返回创建的订单信息', res)
        if(res.meta.status !== 200) return uni.$showMsg('订单创建失败！');
        // 得到服务器响应的订单号
        const order_number = res.message.order_number
        
        /** 
         * 订单预支付：发起请求获取订单的预支付信息，
         * 如：nonceStr, package, paySign, timeStamp, signType
         */
        // 调用统一下单接口发起预支付，获取预支付信息
        const {data: res2} = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {order_number})  // 这里在后端thinkphp配置了路由映射
        console.log('返回订单预支付信息', res2)
        if(res2.meta.status !== 200) return uni.$showMsg('订单' + order_number + '预支付失败！');
        // 保存预支付信息
        const payInfo = res2.message.pay
        console.log('payInfo', payInfo)
        
        // 发起支付
        const [err, succ] = await uni.requestPayment(payInfo)
        if(err) {
          console.log('订单支付失败', err)
          switch(err.errMsg) {
            case 'requestPayment:fail cancel':
              return uni.$showMsg('您已取消了支付！', 1500, 'error')
              break;
            default:
              return uni.$showMsg('订单支付失败！\n' + JSON.stringify(err))
              break;
          }
        }
        console.log('订单已支付！', succ)
        
        // 支付后，发起查询订单接口请求
        const {data: res3} = await uni.$http.post('/api/public/v1/my/orders/chkorder', {order_number})
        console.log('订单查询接口返回结果', res3)
        
        if(res3.meta.status === 200 || (res3.message.return_code === 'SUCCESS' && res3.message.result_code === 'SUCCESS' && res3.message.trade_state === 'SUCCESS')) {
          uni.$showMsg('订单支付成功！', 1500, 'success')
          // 删除购物车中已勾选结算的商品
          this.cart.forEach((item, index, arr) => {
            if(item.goods_state) this.removeGoodsById(item)
          })
          // 2秒后跳转到【我的】页面
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/my/my'
            })
          }, 2000)
        } else {
          return uni.$showMsg('订单查询结果返回失败！\n' + JSON.stringify(res3.message))
        }
        
        // 最后：记得恢复配置请求根路径前缀
        uni.$http.baseUrl = 'https://www.uinav.com'
      },
      // 购物车点击结算未登录的提示函数
      showTips(n) {
        uni.showToast({
          title: '请登录后再结算！' + n + '秒后自动跳转到登录页面...',
          icon: 'none',
          mask: true,
          duration: 1500
        })
      }
    }
  }
</script>

<style lang="scss">
.my-settle-container {
  position: fixed;
  z-index: 999;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  background-color: #FFFFFF;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  padding-left: 5px;
  .radio {
    display: flex;
    align-items: center;
  }
  .amount-box {
    .amount-title {}
    .amount-num {
      color: #C00000;
      font-weight: bold;
    }
  }
  .btn-settle {
    background-color: #C00000;
    color: #FFFFFF;
    height: 50px;
    padding: 0 10px;
    min-width: 100px;
    line-height: 50px;
    text-align: center;
  }
}
</style>
